<template>
	<view class="upload-file" @click="openCamera" :style="{backgroundColor}">
		<!-- <image mode="aspectFill"></image> -->
		<slot></slot>
	</view>
</template>

<script setup>
import {useCheckIfFileIsImageOrVideo} from '../utils/useCheckIfFileIsImageOrVideo'
const props = defineProps(['imgUrl', 'showList', 'backgroundColor'])
//h5
function recursionCompressH5(url, callback) {
	for (let itemImg of url) {
		getUserImageCompressH5(itemImg,callback)
	}
}

// h5压缩图片
function getUserImageCompressH5 (imgUrl,callback) {
	console.log(imgUrl, "| imgUrl");
	return new Promise((resolve, reject)=>{
		uni.getImageInfo({
			src: imgUrl,
			success(res) {
				let canvasWidth = res.width; //图片原始长宽
				let canvasHeight = res.height;
				let img = new Image();
				img.src = res.path;
				let canvas = document.createElement("canvas");
				let ctx = canvas.getContext("2d");
				canvas.width = canvasWidth / 2;
				canvas.height = canvasHeight / 2;
				ctx.drawImage(img, 0, 0, canvasWidth / 2, canvasHeight / 2);
				canvas.toBlob(function(fileSrc) {
					let imgSrc = window.URL.createObjectURL(fileSrc);
					console.log(imgSrc, "| imgSrc");
				});
			}
		});
	})
}


const openCamera = () => {
		// #ifdef H5
		let tempList = []
		uni.chooseImage({
			sizeType: ['compressed'],
			sourceType: ['album', 'camera'],
			success: (res) => {				
				if (res.tempFiles?.length > 0) {
					uploadFile(res?.tempFiles)
					// tempList = res.tempFilePaths
					// recursionCompressH5(tempList, (e) => {
					// 	console.log('压缩后结果-----', e)
					// })
				}
			},
			fail: (err) => {
				console.log("err: ------", err);
			}
		})
		// #endif
		// #ifdef MP-WEIXIN
		uni.chooseMedia({
			count: 9,
			mediaType: ['image', 'video'],
			sourceType: ['album', 'camera'],
			maxDuration: 30,
			camera: 'back',
			success(chooseImageRes) {
				console.log(chooseImageRes, "｜ chooseImageRes");
				chooseImageRes.tempFiles.forEach((fileRes) => {
					const {
						tempFilePath,
						size
					} = fileRes
					uploadFile({
						tempFilePath,
						size
					})
				})
			}
		})
		// #endif
		
		function uploadFile(fileData) {
			let tempFilePath = null
			if(Array.isArray(fileData)) {
				const formData = new FormData()
				formData.append('size', fileData[0])
				tempFilePath = fileData[0].path
			}
			uni.uploadFile({
				url: 'http://localhost:9081/attach/upload',
				filePath: tempFilePath || fileData.tempFilePath,
				name: 'file',
				formData: {
					...fileData
				},
				success: (uploadFileRes) => {
					const {
						data,
						code
					} = JSON.parse(uploadFileRes.data)
					if(code === '0') {
						props.showList.push({
							...props.showList,
							url: data.url,
							type: useCheckIfFileIsImageOrVideo(data.url),
							flag: true,
						})
					}
				}
			})
		}
	}
</script>

<style lang="scss" scoped>
.upload-file {
	width: 100%;
	height: 100%;
	display: flex;
	align-items: center;
	justify-content: center;
	> image {
		width: 100%;
		height: 100%;
	}
}
</style>